/**
 * Created by TomSean on 2017/3/7.
 */
var VehicleInfo = function (id, $list) {
    if (id == undefined || !id) {
        this.id = "d-" + new Date().getTime();
    } else {
        this.id = id;
    }
    this.$list = $list;
    return this;
}
VehicleInfo.prototype = {
    addToList: function ($p) {
        $p.createTr(this.$list.find("tbody"), this.id);
    }
}
/* 车主信息管理对象 */
var OwnerManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
OwnerManager.prototype = {
    init: function () {
        var /* 将.search-params里的参数绑定到kendo控件里 */
            bindFieldArray = this.sysUtils.getBindFieldArray(this.$parent.find(".search-panel"));
        var /* 初始化按钮列表 */ bindFunctionArray = [
            {fName: "search", fs: this.findData},
            {fName: "reset_btn", fs: this.resetInfo},
            {fName: "recharge", fs: this.recharge},
            {fName: "download_template", fs: this.downloadTemplate}
        ];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        var sHeight = (this.$parent.find('.search-panel')[0].clientHeight);
        var allHeight = (this.$parent.find('.resource-panel')[0].clientHeight);
        this.$parent.find('#owner-info-data-list').height(allHeight - sHeight - 2);
        this.initTable();
        this.treeView();
    },
    recharge: function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data("that");
        }
        var id = $this.selectRowId;
        if (!id || id == undefined) {
            notification({title: "操作失败", message: "请选择要充值的车主!!"}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + "owner_info/" + id, null, "json", function (res) {
            $this.entity = res[0];
            $this.rechargeDiv = $this.sysUtils.openWindow($this.rechargeDiv, {
                title: '充值缴费中心',
                width: '555px',
                height: '520px',
                resizeable: false,
                content: '/views/parkLotCenter/parkingLotInfo/recharge.html'
            }, true);
        });
    },
    downloadTemplate: function (e) {
        window.open(baseApiPath + 'owner_info/download_template');
    },
    exportOwner: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var orgCode = _this.nodeInfo.organizationCode;
        var /* 从kendo控件里将绑定的参数转为json字符串 */ params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        if (validityForm(_this.$parent)) {
            if (!isEmpty(params["minDate"])) {
                params["minDate"] = params["minDate"].pattern("yyyy-MM-dd");
            }
            if (!isEmpty(params["maxDate"])) {
                params["maxDate"] = params["maxDate"].pattern("yyyy-MM-dd");
            }
            if (!isEmpty(orgCode)) {
                params['organizationCode'] = orgCode;
            }
            var url = baseApiPath + "owner_info/export/owner";
            window.open(url + '?json=' + encodeURI(JSON.stringify(params)));
        }
    },
    exportOrganization: function (e) {

    },
    batchRenewal: function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var /* 从kendo控件里将绑定的参数转为json字符串 */ params = $this.sysUtils.getBindDocJson($this.bindBaseModels.bindFieldArray);
        var orgCode = $this.nodeInfo.organizationCode;
        params['organizationCode'] = orgCode;
        JsonpAjax(baseApiPath + 'owner_info/batch_renewal/list', JSON.stringify(params), 'json', function (res) {
            $this.ownerList = res;
            $this.renewalDiv = $this.sysUtils.openWindow($this.renewalDiv, {
                title: '批量续费',
                width: '800px',
                height: '600px',
                resizeable: false,
                content: '/views/parkLotCenter/parkingLotInfo/batch_renewal.html'
            }, true);
        }, false);

    },
    inputOwner: function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.editDiv = $this.sysUtils.openWindow($this.editDiv, {
            title: "上传车主数据",
            height: "600px",
            width: "480px",
            resizable: false,
            content: "/views/parkLotCenter/parkingLotInfo/upload_owner.html"
        }, true);
    },
    inputOrganization: function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.editDiv = $this.sysUtils.openWindow($this.editDiv, {
            title: "上传组织数据",
            height: "600px",
            width: "480px",
            resizable: false,
            content: "/views/parkLotCenter/parkingLotInfo/upload_organization.html"
        }, true);
    },
    /*
     * 重置按钮
     */
    resetInfo: function (e) {
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    removeOrganization: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        notification({title: "确认信息", message: "确定需要删除选中的组织机构？"}, 'confirm', {
            callback: function () {
                var $treeView = _this.$parent.find("#owner-organization-tree").data("kendoTreeView");
                _this.$treeView = $treeView;
                var curNode = $treeView.select();
                var parentItem = $treeView.dataItem(curNode);
                JsonpAjax(baseApiPath + "pbaOwnerOrganization/Del/" + parentItem["id"], undefined, "GET", "json", null, function (res) {
                    // $treeView.select($treeView.dataItems()[0]);
                    $treeView.select($treeView.findByUid($treeView.dataItems()[0].uid));
                    $treeView.remove(curNode);
                });
            }
        });
    },
    findData: function (e, code) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        if (code == undefined || isEmpty(code)) {
            code = "null";
            if (_this.nodeInfo.organizationCode) {
                code = _this.nodeInfo.organizationCode;
            }
        }
        var /* 从kendo控件里将绑定的参数转为json字符串 */ params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        if (validityForm(_this.$parent)) {
            if (!isEmpty(params["minDate"])) {
                params["minDate"] = params["minDate"].pattern("yyyy-MM-dd");
            }
            if (!isEmpty(params["maxDate"])) {
                params["maxDate"] = params["maxDate"].pattern("yyyy-MM-dd");
            }
            var url = baseApiPath + "pbaOwnerVehicleInfo/queryWithPage/" + code;
            var grid = _this.$parent.find("#owner-info-data-list").data("kendoGrid");
            // var dataT = {curdatetime:new Date().getTime(), json:JSON.stringify(params)};
            params["curdatetime"] = new Date().getTime();
            var dataSource = _this.sysUtils.getDataSource({url: url, data: params, dataType: "GET"});
            grid.setDataSource(dataSource);
        }
    },
    updateData: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        var id = _this.selectRowId;
        if (!id || id == undefined) {
            notification({title: "操作失败", message: "请选择要修改的车主信息!!"}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + "owner_info/" + id, null, "json", function (res) {
            _this.entity = res[0];
            _this.vehicleinfo = res[1];
            _this.openEditWindow("修改车主信息");
        });
    },
    deleteData: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        var ids = "";
        _this.$parent.find("input[name=\"owner-info-code\"]:checked").each(function (inx, itm) {
            var id = $(itm).val();
            ids += id + ",";
        });
        if (ids == "") {
            notification({title: "操作失败", message: "请选择至少一条需要删除的记录!!"}, 'info');
            return;
        }
        notification({title: "确认信息", message: "确定需要删除选中的信息？"}, 'confirm', {
            callback: function () {
                JsonpAjax(baseApiPath + "owner_info/delete?ownerCode=" + ids, "", "json", function (res) {
                    _this.findData(e, _this.nodeInfo.organizationCode);
                });
            }
        });
    },
    createData: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        _this.entity = undefined;
        _this.vehicleinfo = undefined;
        _this.openEditWindow("新增车主信息");
    },
    initTable: /* 初始化表格(kendo-Grid) */ function () {
        var _this = this;
        var columns = [
            {
                width: 30,
                headerTemplate: '<input type="checkbox" gridId="owner-info-data-list" onclick="gridCheckAll(this)" />',
                template: '<input type="checkbox" name="owner-info-code" value="${ownerCode}" />'
            },
            {
                width: 100,
                title: "车主编号",
                field: "ownerCode"
            },
            {
                width: 90,
                title: "车主姓名",
                field: "ownerName"
            },
            {
                width: 120,
                title: "拥有车辆",
                field: "vehicleNos"
            },
            {
                title: "所属组织",
                template: "${organizationName == null ? '暂无所属组织' : organizationName}"
            },
            {
                width: 120,
                title: "联系电话",
                field: "ownerPhone"
            },
            {
                width: 180,
                title: "创建时间",
                field: "createTime"
            },
            {
                width: 150,
                title: "创建操作人",
                field: "createUsername"
            }
        ];
        this.sysUtils.createGird(
            this.$parent.find("#owner-info-data-list"),
            {
                selectable: 'single',
                autoSync: true,
                columnMenu: true,
                reorderable: true,
                resizable: true,
                pageable: {input: true, numeric: false},
                columns: columns,
                change: function (e) {
                    var selected = $.map(this.select(), function (itm) {
                        return $(itm).find("input[type=checkbox]").val();
                    });
                    _this.selectRowId = selected[0];
                },
                dataBound: function () {
                    var $list = _this.$parent.find("#owner-info-data-list");
                    $list.find("tr").unbind("dblclick");
                    $list.find("tr").dblclick(function (e) {
                        var grid = $list.data("kendoGrid");
                        var dataItem = grid.dataItem(grid.select());
                        //打开查看窗口
                        _this.isEdit = false;
                        _this.openReadWindow(dataItem["ownerCode"]);
                    });
                }
            }
        )
    },
    treeView: function () {
        var _this = this;
        var homogeneous = new kendo.data.HierarchicalDataSource({
            transport: {
                read: {
                    url: baseApiPath + 'pbaOwnerOrganization/selectByParentOrgCode',
                    dataType: "json"
                }
            },
            schema: {
                model: {
                    id: "organizationCode",
                    hasChildren: "hasChildren",
                },
                data: function (response) {
                    return response.data;
                },
                total: function (response) {
                    return response.data.total;
                }
            }
        });
        _this.$parent.find("#owner-organization-tree").kendoTreeView({
            dataSource: homogeneous,
            dataTextField: "organizationName",
            select: function (e) {
                var item = this.dataItem(e.node);
                _this.nodeInfo = item;
                _this.findData(null, item.organizationCode);
            },
            dataBound: function (res) {
                if (_this.nodeInfo == null) {
                    this.expand(".k-item.k-first");
                    var nodes = this.dataSource.view();
                    var node = this.findByUid(nodes[0]["uid"]);
                    this.select(node);
                    // _this.$parent.find('.k-item.k-first').click();
                    _this.nodeInfo = nodes[0];
                    _this.findData(null, _this.nodeInfo.organizationCode);
                }
            }
        });
        // JsonpAjax(baseApiPath + "owner_info/organization/select", null, "json",
        //     function(res) {
        //         if (res.length < 1) {
        //             return;
        //         }
        //         _this.$parent.find("#owner-organization-tree").kendoTreeView({
        //             dataTextField : "fullName",
        //             dataSource : res,
        //             schema : {
        //                 model : {
        //                     hasChildren : "hasChildren",
        //                     id : "id",
        //                     children : "items",
        //                     expanded : false
        //                 }
        //             },
        //             select : function(e) {
        //                 var item = this.dataItem(e.node);
        //                 _this.nodeInfo = item;
        //                 _this.findData(null, item.dataCode);
        //             },
        //             dataBound : function (res) {
        //                 if (_this.nodeInfo == null) {
        //                     var nodes = this.dataSource.view();
        //                     var node = this.findByUid(nodes[0]["uid"]);
        //                     this.select(node);
        //                     _this.nodeInfo = nodes[0];
        //                     _this.findData(null, _this.nodeInfo.organizationCode);
        //                 }
        //             }
        //         });
        //         _this.$treeView = _this.$parent.find("#owner-organization-tree").data("kendoTreeView");
        //     },true);
    },
    openReadWindow: function (id) {
        var _this = this;
        JsonpAjax(baseApiPath + "owner_info/" + id, null, "json", function (res) {
            _this.entity = res[0];
            _this.vehicleinfo = res[1];
            _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
                title: "查看车主信息",
                height: "600px",
                width: "850px",
                resizable: false,
                content: "views/parkLotCenter/parkingLotInfo/owner_info_edit.html"
            }, true);
        });
    },
    openEditWindow: function (title) {
        var _this = this;
        _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
            title: title,
            height: "600px",
            width: "850px",
            resizable: false,
            content: "views/parkLotCenter/parkingLotInfo/owner_info_edit.html"
        }, true);
    },
    openOrganizationEditWindow: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        _this.$treeView = _this.$parent.find("#owner-organization-tree").data("kendoTreeView");
        _this.organizationDiv = _this.sysUtils.openWindow(_this.organizationDiv, {
            title: "添加组织机构信息",
            height: "300px",
            width: "380px",
            resizeable: false,
            content: "views/parkLotCenter/parkingLotInfo/organization_info.html"
        }, true);
    }
}

var OrganizationEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
OrganizationEdit.prototype = {
    init: function () {
        var bindField = this.sysUtils.getBindFieldArray(this.$parent);
        var bindFunctionField = [
            {fName: "save_organization_info", fs: this.addOrganization},
            {
                fName: "cancel_organization_info", fs: function () {
                    $("#" + ownerManager.organizationDiv).data("kendoWindow").close()
                }
            }
        ];
        this.bindBaseModels = new bindBaseModel(null, bindField, bindFunctionField, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        var $treeView = ownerManager.$treeView;
        var curNode = $treeView.select();
        var parentItem = $treeView.dataItem(curNode);
        this.$parent.find("#cur_parent_organization_id").html(parentItem["organizationCode"]);
        this.$parent.find("#cur_parent_organization_name").html(parentItem["organizationName"]);
    },
    addOrganization: function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        var $treeView = ownerManager.$treeView;
        var curNode = $treeView.select();
        var parentItem = $treeView.dataItem(curNode);
        var organizationId = _this.$parent.find('#owner_organization_id').val();
        var organizationName = _this.$parent.find("#owner_organization_name").val();
        if (!organizationName || organizationName == undefined || organizationName == '') {
            notification({title: "操作失败", message: "组织名称不能为空"}, "info");
            return;
        }
        var data = {
            'organizationId': organizationId,
            'organizationName': organizationName,
            'parentOrganizationCode': parentItem["id"]
        };
        JsonpAjax(baseApiPath + "pbaOwnerOrganization/Add", JSON.stringify(data), "POST", "json", "application/json", function (res) {
            $treeView.append({
                'id': res.data.organizationCode,
                'organizationCode': res.data.organizationCode,
                'organizationName': organizationName + "(" + res.data.organizationCode + ")",
                'hasChildren': false
            }, curNode);
            $("#" + ownerManager.organizationDiv).data("kendoWindow").close();
        });
    }
}